﻿using UnityEngine;

public class PlayerController : MonoBehaviour
{

    public float speed = 6f;
    public float jump = 8f;

    [Header("地面判定")]
    public Vector2 centerPointOffset;       // 角色中心点的偏移量
    public Vector2 overlapBoxSize;          // 检测盒子大小，盒子与地面接触的部分可以多增加一些，这样能够提供更宽松的起跳检测
    public LayerMask groundLayerMask;       // 地面的 LayerMask

    public bool isOnGround;

    private Rigidbody2D rb;
    private SpriteRenderer sr;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        sr = GetComponent<SpriteRenderer>();
    }

    void Update()
    {
        float x = Input.GetAxis("Horizontal");
        float y = Input.GetAxis("Vertical");
        float rawX = Input.GetAxisRaw("Horizontal");
        float rawY = Input.GetAxisRaw("Vertical");

        Move(x, rawX);
        Jump(y, rawY);
    }


    void Move(float x, float rawX)
    {
        if (rawX != 0)
        {
            if (x > Mathf.Epsilon)
            {
                sr.flipX = false;

            }
            else if (x < -Mathf.Epsilon)
            {
                sr.flipX = true;
            }
            rb.velocity = new Vector2(x * speed, rb.velocity.y);
        }
        else if (rawX == 0)
        {
            rb.velocity = Vector2.Lerp(rb.velocity, (new Vector2(x * speed, rb.velocity.y)), 10 * Time.deltaTime);
        }
    }


    void Jump(float y, float rawY)
    {
        isOnGround = CheckOnGround();
        if (!isOnGround)
        {
            return;
        }
        if (y > 0.1f)
        {
            rb.velocity = new Vector2(rb.velocity.x, jump);
        }
    }

    bool CheckOnGround()
    {
        Collider2D hitCollider = Physics2D.OverlapBox((Vector2)transform.position + centerPointOffset, overlapBoxSize, 0, groundLayerMask);
        return hitCollider != null;
    }

    // 显示判定框
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireCube((Vector2)transform.position + centerPointOffset, overlapBoxSize);
    }
}
